package main

import (
	"context"
	"dbaUtils/libs"
	"flag"
	"github.com/siddontang/go-mysql/mysql"
	"github.com/siddontang/go-mysql/replication"
	"os"
	"strconv"
)

var (
	ServerID  int
	Flavor string
	Host string
	Port int
	User string
	Password string
	binlog string
	pos int
	logger string
)

func init() {
	flag.IntVar(&ServerID, "ServerID", 1, "服务器的全局ID")
	flag.StringVar(&Flavor, "Flavor", "mysql", "请选择mysql或者mariadb")
	flag.StringVar(&Host, "Host", "127.0.0.1", "服务器地址")
	flag.IntVar(&Port, "Port", 3306, "数据库端口")
	flag.StringVar(&User, "User", "root", "用户名")
	flag.StringVar(&Password, "Password", "", "密码")
	flag.StringVar(&binlog, "binlog", "", "要查看的binlog")
	flag.IntVar(&pos, "pos", 4, "事件起始位置")
	flag.StringVar(&logger, "logger", "", "日志位置")
}


func main() {
	flag.Parse()
	config := replication.BinlogSyncerConfig{
		ServerID: uint32(ServerID),
		Flavor: Flavor,
		Host: Host,
		Port: uint16(Port),
		User: User,
		Password: Password,
	}
	syncer := replication.NewBinlogSyncer(config)
	Streamer, _ := syncer.StartSync(mysql.Position{binlog, uint32(pos)})


	for {
		ev, err := Streamer.GetEvent(context.Background())
		if err!= nil {
			libs.CheckErrors("获取binlog解析错误！", err)
		}
		libs.CheckErrors("文件创建错误", err)

		ev.Dump(os.Stdout)

		pos := strconv.FormatUint(uint64(ev.Header.LogPos), 10)

		f, _ := os.Create(logger)
		_, err = f.Write([]byte(pos))
		libs.CheckErrors("写入文件错误", err)
		err = f.Close()
		libs.CheckErrors("关闭文件错误", err)
	}
}